package wangwenjun.phase2.concurrencypattern.activeobject.staticproxy.framework;

import lombok.extern.slf4j.Slf4j;
import wangwenjun.phase2.concurrencypattern.activeobject.staticproxy.OrderService;
import wangwenjun.phase2.concurrencypattern.future.Future;
import wangwenjun.phase2.concurrencypattern.future.FutureImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ChangLiang
 * @date 2020/6/17
 */
@Slf4j
class OrderServiceProxy implements OrderService {

    private final OrderService orderService;

    private final OrderServiceMessageQueue orderServiceMessageQueue;

    public OrderServiceProxy(OrderService orderService, OrderServiceMessageQueue orderServiceMessageQueue) {
        this.orderService = orderService;
        this.orderServiceMessageQueue = orderServiceMessageQueue;
    }

    /**
     * Queue 中提交一个对应的Message 信息，这个工作主要是由Proxy 完成的
     * 为了让Proxy 的构造透明化，我们需要设计一个Factory 工具类
     */

    @Override
    public void createOrder(String account, long orderId) {
        // 收集方法参数，并且封装成MethodMessage ，然后offer 至队列中
        Map<String, Object> params = new HashMap<>(2);
        params.put("account", account);
        params.put("orderId", orderId);
        OrderServiceMessage message = new OrderCreateMessage(params, orderService);
        orderServiceMessageQueue.offer(message);
    }

    @Override
    public Future<String> findOrderDetails(long orderId) {
        // 定义一个FutureImpl 支持立即返回
        FutureImpl<String> future = new FutureImpl<>();
        log.info("Thread:{} OrderServiceProxy#futureImpl:{}", Thread.currentThread(), future.toString());
        Map<String, Object> params = new HashMap<>(2);
        params.put("orderId", orderId);
        params.put("future", future);
        OrderDetailsMessage message = new OrderDetailsMessage(params, orderService);
        orderServiceMessageQueue.offer(message);
        return future;
    }
}
